var stats = new Stats(),
    c = document.getElementById('c'),
    ctx = c.getContext('2d'),
    GRAVITY_FORCE = 9.81,
    WIDTH_AS_METER = 10,
    pixelPerMeter = 0,
    fps,
    calculationParameters = {
        power: 0, //初始力，单位 N
        angle: 0, //力、速度的角度（方向）
        InitVelocity: 0, //初速度
        lastTime: 0, //上一次次计算时间
        score: 0, //得分
    },
    hitBall = new Vector(0, 0);
    hitBall.r = 20;
window.addEventListener('resize', handleWindowResize, false);
function handleWindowResize () {
    c.width = window.innerWidth * window.devicePixelRatio;
    c.height = window.innerHeight * window.devicePixelRatio;
    pixelPerMeter = c.width / WIDTH_AS_METER;
    hitBall.set({
        x: c.width / 2,
        y: c.height / 2 + 200
    })
}
handleWindowResize();

var animationTimer = new Sprite.AnimationTimer(5000);

function drawBall (sprite, ctx) {
    ctx.save();
    ctx.fillStyle = 'red';
    ctx.beginPath();
    ctx.arc(sprite.x, sprite.y, sprite.r, 0, Math.PI * 2, false);
    ctx.closePath();
    ctx.fill();
    ctx.restore();
}
var drawBallPainter = new Sprite.StrokeAndFillPainter(drawBall);
var ball = new Sprite('ball', drawBallPainter);

function fallDownBehaivor (sprite, behavior, ctx, time) {
    if(animationTimer.isRunning()) {
        time = animationTimer.getElapsedTime() / 1000;
        sprite.speed.set({
            x: 0,
            y: pixelPerMeter * GRAVITY_FORCE * time / fps
        });
        sprite.add(sprite.speed);
        if(behavior.hitTest()) {
            animationTimer.stop();
        }
    }
    
}
ball.addBehavior(fallDownBehaivor, {
    hitTest: function () {
        var distance = ball.modeTo(hitBall);
        console.log(distance);
        //返回true时，碰撞已经发生，即 事后碰撞检测
        return distance < ball.r + hitBall.r;
    }
});

ball.set({
    x: c.width / 2,
    y: 100
})
ball.r = 20;

function drawHitBall (ctx) {
    ctx.save();
    ctx.fillStyle = 'blue';
    ctx.beginPath();
    ctx.arc(hitBall.x, hitBall.y, hitBall.r, 0, Math.PI * 2, false);
    ctx.closePath();
    ctx.fill();
    ctx.restore();
}

function loop () {
    ctx.clearRect(0, 0, c.width, c.height);
    requestAnimationFrame(loop);
    var tempFps = stats.update();
    fps = tempFps === 0 ? 60 : tempFps;
    ball.paint(ctx);
    ball.update(ctx);
    drawHitBall(ctx);
}

animationTimer.start();
requestAnimationFrame(loop);